package com.tepth.remote.control.delegate.home;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.ContentObserver;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatImageButton;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.crashreport.CrashReport;
import com.tepth.remote.control.R;
import com.tepth.remote.control.R2;
import com.tepth.remote.control.base.bean.SubordinateCount;
import com.tepth.remote.control.base.bean.SubordinateGps;
import com.tepth.remote.control.base.config.SpKey;
import com.tepth.remote.control.base.event.CalendarEvent;
import com.tepth.remote.control.base.event.LocationEvent;
import com.tepth.remote.control.base.event.RequestLocationEvent;
import com.tepth.remote.control.base.map.overlay.MarkerOverlay;
import com.tepth.remote.control.base.mvp.BaseMvpDelegate;
import com.tepth.remote.control.delegate.apply.create.ApplyCreateDelegate;
import com.tepth.remote.control.delegate.apply.history.ApplyHistoryDelegate;
import com.tepth.remote.control.delegate.apply.list.ApplyListDelegate;
import com.tepth.remote.control.delegate.attendance.AttendanceDelegate;
import com.tepth.remote.control.delegate.file.FileDelegate;
import com.tepth.remote.control.delegate.pick.PickDelegate;
import com.tepth.remote.control.delegate.picture.list.PictureListDelegate;
import com.tepth.remote.control.delegate.picture.upload.PictureUploadDelegate;
import com.tepth.remote.control.manager.ConfigManager;
import com.tepth.remote.control.service.LineStatus;
import com.tepth.remote.core.app.Control;
import com.tepth.remote.core.net.CommonParams;
import com.tepth.remote.core.utils.storage.ControlPreference;
import com.tepth.remote.ui.alert.DialogLoader;
import com.tepth.remote.ui.alert.IDialogClickListener;
import com.tepth.remote.ui.recycler.ItemType;
import com.tepth.remote.ui.recycler.MultipleFields;
import com.tepth.remote.ui.recycler.MultipleItemEntity;
import com.tepth.remote.ui.recycler.MultipleRecyclerAdapter;
import com.tepth.remote.ui.recycler.MultipleRecyclerClickListener;
import com.tepth.remote.ui.recycler.grid.GridItemBean;
import com.tepth.remote.ui.recycler.grid.GridItemType;
import com.yqritc.recyclerviewflexibledivider.VerticalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description:
 *
 * @author Hequn.Lee
 * @date 2018/11/9
 */
@SuppressLint("SetTextI18n")
public class HomeDelegate extends BaseMvpDelegate<HomePresenter> implements HomeContract.View, MultipleRecyclerClickListener {

    @BindView(R2.id.home_text_name)
    AppCompatTextView textName = null;
    @BindView(R2.id.home_text_status)
    AppCompatTextView textStatus = null;
    @BindView(R2.id.home_text_date)
    AppCompatTextView textDate = null;
    @BindView(R2.id.home_recycler_view)
    RecyclerView recyclerView = null;
    @BindView(R2.id.mapView)
    MapView mMapView = null;

    @BindView(R2.id.home_text_total)
    AppCompatTextView textTotal = null;
    @BindView(R2.id.home_text_online)
    AppCompatTextView textOnline = null;
    @BindView(R2.id.home_text_apply)
    AppCompatTextView textApply = null;
    @BindView(R2.id.home_text_outline)
    AppCompatTextView textOutline = null;
    @BindView(R2.id.home_text_out_today)
    AppCompatTextView textOutTotal = null;
    @BindView(R2.id.tv_other)
    AppCompatTextView textOther = null;
    @BindView(R2.id.layout_subordinate_count)
    LinearLayoutCompat layoutSubordinateCount = null;
    @BindView(R2.id.linear_home_lat_lng)
    LinearLayoutCompat layoutLatLng = null;
    @BindView(R2.id.text_home_lat_lng)
    AppCompatTextView textLatLng = null;
    @BindView(R2.id.image_button_subordinate_location)
    AppCompatImageButton imageButtonSubordinateLocation = null;
    @BindView(R2.id.image_button_subordinate_refresh)
    AppCompatImageButton imageButtonSubordinateRefresh = null;
    @BindView(R2.id.image_button_center)
    AppCompatImageButton imageButtonCenter = null;
    /**
     * 百度地图控件
     */
    private BaiduMap mBaiduMap;
    /**
     * 是否第一次定位
     */
    private boolean isFirstLoc = true;

    /**
     * 是否显示下属人员位置
     */
    private boolean showSubordinateLocation = false;

    private DialogLoader mDialogLoader = null;

    @Override
    public Object setLayout() {
        return R.layout.delegate_home;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mDialogLoader = new DialogLoader(getProxyActivity());
        EventBus.getDefault().register(this);
        final String realName = ControlPreference.getPreferenceString(SpKey.KEY_REAL_NAME);
        textName.setText(StringUtils.isEmpty(realName) ? "未知姓名" : realName);
        initViewPagerData();
        initMap();
        if (SpKey.KEY_BOOLEAN_TRUE.equals(ConfigManager.getInstance().getIsZj())
                || SpKey.KEY_BOOLEAN_TRUE.equals(ConfigManager.getInstance().getIsBm())) {
            mPresenter.getSubordinateNumber(ConfigManager.getInstance().getUid() + "");
            layoutSubordinateCount.setVisibility(View.VISIBLE);
            imageButtonSubordinateLocation.setVisibility(View.VISIBLE);
            imageButtonSubordinateRefresh.setVisibility(View.VISIBLE);
        } else {
            layoutSubordinateCount.setVisibility(View.GONE);
            imageButtonSubordinateLocation.setVisibility(View.GONE);
            imageButtonSubordinateRefresh.setVisibility(View.GONE);
        }
        //初始化时间
        setCalendarOnTextView(TimeUtils.getNowString());
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        CrashReport.setUserId(ConfigManager.getInstance().getPhoneId());
        //检查自启动
        checkBootComplete();
    }

    /**
     * 初始化ViewPager数据
     */
    private void initViewPagerData() {
        final ArrayList<GridItemBean> homeGridData = new ArrayList<>();
        homeGridData.add(new GridItemBean(GridItemType.ATTENDANCE, "{icon-location}", "现场考勤"));
        homeGridData.add(new GridItemBean(GridItemType.HISTORY, "{icon-history-notification}", "历史通知"));
        homeGridData.add(new GridItemBean(GridItemType.CAMERA, "{icon-camera}", "拍照上传"));
        homeGridData.add(new GridItemBean(GridItemType.FILE, "{icon-down-file}", "文件下载"));
        final ArrayList<GridItemBean> nextGridData = new ArrayList<>();
        nextGridData.add(new GridItemBean(GridItemType.PICTURE, "{icon-image}", "图片查看"));
        if (SpKey.KEY_BOOLEAN_TRUE.equals(ConfigManager.getInstance().getIsZj())
                || SpKey.KEY_BOOLEAN_TRUE.equals(ConfigManager.getInstance().getIsBm())) {
            nextGridData.add(new GridItemBean(GridItemType.PICK, "{icon-seek-point}", "围栏踩点"));
            nextGridData.add(new GridItemBean(GridItemType.SHOW_APPLY, "{icon-history-apply}", "查看申请"));
        }
        if (!SpKey.KEY_BOOLEAN_TRUE.equals(ConfigManager.getInstance().getIsBm())) {
            nextGridData.add(new GridItemBean(GridItemType.SEND_APPLY, "{icon-apply}", "请假申请"));
        }
        final ArrayList<MultipleItemEntity> viewPagerData = new ArrayList<>();
        final MultipleItemEntity homeEntity = MultipleItemEntity.builder()
                .setField(MultipleFields.ITEM_TYPE, ItemType.VIEW_PAGER)
                .setField(MultipleFields.VIEW_PAGER_GROUP_LIST, homeGridData)
                .builder();
        final MultipleItemEntity nextEntity = MultipleItemEntity.builder()
                .setField(MultipleFields.ITEM_TYPE, ItemType.VIEW_PAGER)
                .setField(MultipleFields.VIEW_PAGER_GROUP_LIST, nextGridData)
                .builder();
        viewPagerData.add(homeEntity);
        viewPagerData.add(nextEntity);
        //2.声名GridView布局方式  第二个参数代表是3列的网格视图 (垂直滑动的情况下, 如果是水平滑动就代表3行)
        final GridLayoutManager gridLayoutManager = new GridLayoutManager(getProxyActivity(), 1);
        //3.给GridLayoutManager设置滑动的方向
        gridLayoutManager.setOrientation(GridLayoutManager.HORIZONTAL);
        //4.为recyclerView设置布局管理器
        recyclerView.setLayoutManager(gridLayoutManager);
        //一个一个的滑动（完全ViewPager效果）
        final PagerSnapHelper snapHelper = new PagerSnapHelper();
        //其他都与RecyclerView一样，只需要绑定下就行
        snapHelper.attachToRecyclerView(recyclerView);
        final MultipleRecyclerAdapter mAdapter = MultipleRecyclerAdapter.create(viewPagerData, this);
        //设置分割线
        recyclerView.addItemDecoration(new VerticalDividerItemDecoration
                .Builder(getProxyActivity())
                .color(android.R.color.white)
                .size(1)
                .build());
        //设置添加,移除item的动画,DefaultItemAnimator为默认的
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        //4.设置适配器
        recyclerView.setAdapter(mAdapter);
    }

    private void initMap() {
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 隐藏缩放控件
        mMapView.showScaleControl(false);
        // 隐藏比例尺控件
        mMapView.showZoomControls(false);
        //Marker点击事件
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                return true;
            }
        });
        mBaiduMap.setOnMyLocationClickListener(new BaiduMap.OnMyLocationClickListener() {
            @Override
            public boolean onMyLocationClick() {
                if (layoutLatLng != null) {
                    if (layoutLatLng.getVisibility() == View.GONE) {
                        layoutLatLng.setVisibility(View.VISIBLE);
                    } else {
                        layoutLatLng.setVisibility(View.GONE);
                    }
                }
                return true;
            }
        });
    }

    @OnClick({R2.id.image_button_center, R2.id.image_button_subordinate_location,
            R2.id.image_button_subordinate_refresh, R2.id.icon_home_lat_lng_close})
    void onClick(View view) {
        if (view.getId() == R.id.image_button_center) {
            EventBus.getDefault().post(new RequestLocationEvent());
            final MyLocationData locationData = mBaiduMap.getLocationData();
            if (locationData != null) {
                final LatLng latLng = new LatLng(locationData.latitude,
                        locationData.longitude);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(latLng));
            }
        } else if (view.getId() == R.id.image_button_subordinate_location) {
            if (!showSubordinateLocation) {
                showSubordinateLocation = true;
                imageButtonSubordinateLocation.setBackgroundResource(R.mipmap.icon_person_location_after);
                mPresenter.getSubordinateGpsInfo(ConfigManager.getInstance().getUid() + "");
            } else {
                showSubordinateLocation = false;
                imageButtonSubordinateLocation.setBackgroundResource(R.mipmap.icon_person_location_before);
                mBaiduMap.clear();
            }
        } else if (view.getId() == R.id.image_button_subordinate_refresh) {
            mPresenter.getSubordinateNumber(ConfigManager.getInstance().getUid() + "");
            if (!showSubordinateLocation) {
                return;
            }
            mPresenter.getSubordinateGpsInfo(ConfigManager.getInstance().getUid() + "");
        } else {
            if (layoutLatLng != null) {
                if (layoutLatLng.getVisibility() == View.VISIBLE) {
                    layoutLatLng.setVisibility(View.GONE);
                }
            }
        }
    }

    @Override
    public void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        mMapView.onDestroy();
        super.onDestroyView();
    }

    @Override
    public HomePresenter getPresenter() {
        return new HomePresenter(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateLocation(LocationEvent event) {
        if (mBaiduMap != null) {
            final BDLocation location = event.getBDLocation();
            final MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(0)
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            setLatLngOnTextView(location.getLatitude(), location.getLongitude());
            if (isFirstLoc) {
                final MyLocationConfiguration config = new MyLocationConfiguration(
                        MyLocationConfiguration.LocationMode.NORMAL, true, BitmapDescriptorFactory
                        .fromResource(R.mipmap.icon_location));
                mBaiduMap.setMyLocationConfiguration(config);
                isFirstLoc = false;
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(16.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateCanlendar(CalendarEvent event) {
        String status = "";
        switch (event.getLineStatus()) {
            case LineStatus.INIT_STATUS:
                status = "状态：初始化";
                break;
            case LineStatus.ONLINE_STATUS:
                status = "状态：在线";
                break;
            case LineStatus.OUTLINE_STATUS:
                status = "状态：离线";
                break;
            default:
        }
        setCalendarOnTextView(event.getShowCalendar());
        textStatus.setText(status);
    }

    private void setCalendarOnTextView(String showCalendar) {
        textDate.setText(showCalendar.substring(0, showCalendar.indexOf(" ")));
    }

    private void setLatLngOnTextView(double latitude, double longitude) {
        if (textLatLng != null) {
            textLatLng.setText(String.format(Locale.CHINA, "经度：%f", longitude)
                    + " " + String.format(Locale.CHINA, "纬度：%f", latitude));
        }
    }

    @Override
    public void getSubordinateNumberSuccess(SubordinateCount number) {
        textTotal.setText("总数：" + number.getTotal());
        textOnline.setText("在线：" + number.getOnLine());
        textApply.setText("请假：" + number.getOnException());
        textOutline.setText("离线(今天)：" + number.getOutLine());
        textOutTotal.setText("离线(超过一天)：" + number.getOutToday());
        textOther.setText("报警：" + number.getOther());
    }

    @Override
    public void getSubordinateNumberFailed(int code, String msg) {
        textTotal.setText("总数：0");
        textOnline.setText("在线：0");
        textApply.setText("请假：0");
        textOutline.setText("离线(今天)：0");
        textOutTotal.setText("离线(超过一天)：0");
        textOther.setText("报警：0");
    }

    @Override
    public void getSubordinateGpsSuccess(ArrayList<SubordinateGps> subordinates) {
        mBaiduMap.clear();
        ArrayList<OverlayOptions> markers = new ArrayList<>();
        for (int i = 0; i < subordinates.size(); i++) {
            final SubordinateGps subordinate = subordinates.get(i);
            final MarkerOptions marker = MarkerOverlay.builderByStatusFromLayout(
                    new LatLng(subordinate.getLatitude(), subordinate.getLongitude()),
                    subordinate.getUserState(), getContext(), subordinate.getUserName());
            markers.add(marker);
        }
        mBaiduMap.addOverlays(markers);
        showSubordinateLocation = markers.size() > 0;
        ToastUtils.showShort("总人员数：" + markers.size());
    }

    @Override
    public void getSubordinateGpsFailed(int code, String msg) {
        mBaiduMap.clear();
        ToastUtils.showShort("总人员数：0");
    }

    @Override
    public void detectionSuccess(String result) {
        try {
            final JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject.getInteger("Code") == CommonParams.SUCCESS_CODE_NORMAL) {
                if (AppUtils.getAppVersionCode() != jsonObject.getInteger("Version")) {
                    //检查更新
                    Beta.checkUpgrade();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            //检查更新
            Beta.checkUpgrade();
        }
    }

    @Override
    public void detectionFailed(int code, String msg) {
        //检查更新
        Beta.checkUpgrade();
    }

    @Override
    public void showLoading(String str) {

    }

    @Override
    public void hideLoading() {

    }

    /**
     * 重写返回按键
     *
     * @return true处理掉事件
     */
    @Override
    public boolean onBackPressedSupport() {
        final PackageManager pm = getProxyActivity().getPackageManager();
        final ResolveInfo homeInfo = pm.resolveActivity(new Intent(
                Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0);
        final ActivityInfo ai = homeInfo.activityInfo;
        Intent startIntent = new Intent(Intent.ACTION_MAIN);
        startIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        startIntent
                .setComponent(new ComponentName(ai.packageName, ai.name));
        startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Control.getApplicationContext().startActivity(startIntent);
        return true;
    }

    private final ContentObserver mGpsMonitor = new ContentObserver(null) {
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
        }
    };

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        final LocationManager locationManager = (LocationManager) Control.getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        Control.getApplicationContext().getContentResolver()
                .registerContentObserver(
                        Settings.Secure
                                .getUriFor(Settings.System.LOCATION_PROVIDERS_ALLOWED),
                        false, mGpsMonitor);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            mDialogLoader.showWarning("提示", "您没有打开GPS，无法进行定位！是否开启GPS？", new IDialogClickListener() {
                @Override
                public void onClick() {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    mDialogLoader.clearDialog();
                }
            });
        }
        mPresenter.detectionVersion();
    }

    @Override
    public void onclickListener(MultipleFields type, int position) {

    }

    @Override
    public void onLoadRecyclerError(String msg) {

    }

    @Override
    public void onclickViewPagerListener(GridItemType type) {
        switch (type) {
            case ATTENDANCE:
                final MapStatus attendanceStatus = mBaiduMap.getMapStatus();
                start(AttendanceDelegate.create(attendanceStatus.target));
                break;
            case HISTORY:
                start(new ApplyHistoryDelegate());
                break;
            case FILE:
                start(new FileDelegate());
                break;
            case PICTURE:
                start(new PictureListDelegate());
                break;
            case SHOW_APPLY:
                start(new ApplyListDelegate());
                break;
            case SEND_APPLY:
                start(new ApplyCreateDelegate());
                break;
            case PICK:
                final MapStatus pickStatus = mBaiduMap.getMapStatus();
                start(PickDelegate.create(pickStatus.target));
                break;
            case CAMERA:
                start(new PictureUploadDelegate());
                break;
            default:
                break;
        }
    }
}
